﻿using System;
using System.Globalization;
using System.Threading;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
	public class CultureAttribute : ActionFilterAttribute
	{
		private static string _cultureKey;
		private static CultureInfo _defaultCulture;

		public static string CultureKey
		{
			get
			{
				if (string.IsNullOrEmpty(CultureKey))
				{
					_cultureKey = "c";
				}

				return _cultureKey;
			}
			set { _cultureKey = value; }
		}

		public static CultureInfo DefaultCulture
		{
			get
			{
				if (_defaultCulture == null)
				{
					_defaultCulture = new CultureInfo("en-GB");
				}

				return _defaultCulture;
			}
			set { _defaultCulture = value; }
		}

		private CultureInfo GetCulture(string culture)
		{
			if (!string.IsNullOrEmpty(culture))
			{
				return new CultureInfo(culture);
			}

			return DefaultCulture;
		}

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			var culture = string.Empty;

			// Route data.
			if (filterContext.RouteData.Values.ContainsKey(CultureKey))
			{
				culture = filterContext.RouteData.Values[CultureKey] as string;
			}

			// Request data.
			if (string.IsNullOrEmpty(culture))
			{
				culture = filterContext.HttpContext.Request[CultureKey];
			}

			// Session.
			if (string.IsNullOrEmpty(culture))
			{
				culture = filterContext.HttpContext.Session[CultureKey] as string;
			}

			// TODO Get the culture from a cookie.

			SetCulture(GetCulture(culture));
		}

		private void SetCulture(CultureInfo culture)
		{
			Thread.CurrentThread.CurrentCulture = culture;
			Thread.CurrentThread.CurrentUICulture = culture;
		}
	}
}